import { Controller, Post, Body, Logger, Get, Query } from '@nestjs/common';
import { Public } from '@/common/decorators';
import { MonitoringService } from './monitoring.service';
import { MonitoringDataDto, BatchMonitoringDataDto, MonitoringStatsDto } from './dto';

@Controller('trackweb')
export class MonitoringController {
  private readonly logger = new Logger(MonitoringController.name);

  constructor(private readonly monitoringService: MonitoringService) {}

  @Public()
  @Post()
  async receiveData(@Body() data: MonitoringDataDto) {
    try {
      // 保存监控数据到数据库
      await this.monitoringService.saveMonitoringData(data);
      
      // 打印接收到的监控数据
      this.logger.log('收到监控数据:', JSON.stringify(data, null, 2));

      return {
        success: true,
        message: '监控数据已接收并保存',
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      this.logger.error('保存监控数据失败:', error);
      return {
        success: false,
        message: '监控数据保存失败',
        error: error.message
      };
    }
  }

  @Public()
  @Post('batch')
  async receiveBatchData(@Body() batchData: BatchMonitoringDataDto) {
    try {
      const { data } = batchData;
      this.logger.log(`收到批量监控数据，共${data.length}条`);

      // 批量保存监控数据
      await this.monitoringService.saveBatchMonitoringData(data);

      return {
        success: true,
        received: data.length,
        message: '批量监控数据已接收并保存'
      };
    } catch (error) {
      this.logger.error('批量保存监控数据失败:', error);
      return {
        success: false,
        message: '批量监控数据保存失败',
        error: error.message
      };
    }
  }

  /**
   * 获取监控统计信息
   */
  @Get('stats')
  async getStats(@Query() query: MonitoringStatsDto) {
    try {
      const pageVisitStats = await this.monitoringService.getPageVisitStats(query);
      const errorStats = await this.monitoringService.getErrorStats(query);

      return {
        success: true,
        data: {
          pageVisit: pageVisitStats,
          error: errorStats
        }
      };
    } catch (error) {
      this.logger.error('获取监控统计失败:', error);
      return {
        success: false,
        message: '获取监控统计失败',
        error: error.message
      };
    }
  }

  /**
   * 获取今日访问数据
   */
  @Get('today-visits')
  async getTodayVisits() {
    try {
      const stats = await this.monitoringService.getPageVisitStats();
      return {
        success: true,
        data: stats
      };
    } catch (error) {
      this.logger.error('获取今日访问数据失败:', error);
      return {
        success: false,
        message: '获取今日访问数据失败',
        error: error.message
      };
    }
  }
}